﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DotNetNuke.Common;
using ShopSpace.Core;

namespace ShopSpace.UI.DotNetNukeModules.ProjectManagement
{
	public partial class EditProject : EditModuleControlBase
	{
		protected void Page_Load(object sender, EventArgs e)
		{
			try
			{
				this.SetupLinks();
				if (!this.Page.IsPostBack)
				{
					this.SetupForm();
					this.BindProject();
				}
			}
			catch (Exception ex)
			{
				this.HandleException(ex);
			}
		}

		protected void lnkUpdate_Click(object sender, EventArgs e)
		{
			try
			{
				this.SaveProject();
				Response.Redirect(Globals.NavigateURL());
			}
			catch (Exception ex)
			{
				this.HandleException(ex);
			}
		}

		private void SetupLinks()
		{
			this.hlCancel.NavigateUrl = Globals.NavigateURL();
		}

		private void SetupForm()
		{
			
		}

		private void BindProject()
		{
			if (this.editItemId.HasValue)
			{
				Project project = this.ProjectRepository.Get(this.editItemId.Value);
				this.ItemConcurrencyDate = project.ConcurrencyDate;
				this.txtName.Text = project.Name;
			}
		}

		private void SaveProject()
		{
			Project project;
			if (this.editItemId.HasValue)
			{
				project = this.ProjectRepository.Get(this.editItemId.Value);
				project.ConcurrencyDate = this.ItemConcurrencyDate;
				project.Name = this.txtName.Text.Trim();
			}
			else
			{
				project = new Project(this.txtName.Text.Trim(), this.PortalId);
			}

			if (!this.editItemId.HasValue)
			{
				this.ProjectRepository.Add(project, this.UserInfo.Username);
			}
			else
			{
				this.ProjectRepository.Update(project, this.UserInfo.Username);
			}
			this.UserState.AddMessage(this.ModuleId, string.Format("{0} was {1}", project.Name, this.editItemId.HasValue ? "updated" : "added"), DotNetNuke.UI.Skins.Controls.ModuleMessage.ModuleMessageType.GreenSuccess);
		}
	}
}